//
//  YMUtil.m
//  MyProject
//
//  Created by Pei on 16/6/19.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//
#import "YMUtil.h"

@implementation YMUtil

int getIndex (char ch);
BOOL isNumber (char ch);

int getIndex (char ch) {
    if ((ch >= '0'&& ch <= '9')||(ch >= 'a'&& ch <= 'z')||
        (ch >= 'A' && ch <= 'Z')|| ch == '_') {
        return 0;
    }
    if (ch == '@') {
        return 1;
    }
    if (ch == '.') {
        return 2;
    }
    return -1;
}

BOOL isNumber (char ch)
{
    if (!(ch >= '0' && ch <= '9')) {
        return FALSE;
    }
    return TRUE;
}


+ (BOOL) isValidNumber:(NSString*)value{
    const char *cvalue = [value UTF8String];
    int len = (int)strlen(cvalue);
    for (int i = 0; i < len; i++) {
        if(!isNumber(cvalue[i])){
            return FALSE;
        }
    }
    return TRUE;
}

+ (BOOL) isValidPhone:(NSString*)value {
    const char *cvalue = [value UTF8String];
    int len = (int)strlen(cvalue);
    if (len != 11) {
        return FALSE;
    }
    if (![YMUtil isValidNumber:value])
    {
        return FALSE;
    }
    if ([value hasPrefix:@"1"])
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

+ (NSString*)getVersion{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *version = [infoDic objectForKey:@"CFBundleShortVersionString"];
    return version;
}

+ (NSString*)getDeviceNo{
    
    return  [[UIDevice currentDevice] model];
}

+ (NSString*)phoneFormat:(NSString*)phone{
    
    if ([YMUtil validateText:phone]) {
        NSString *firstPart = [phone substringWithRange:NSMakeRange(0, 3)];
        NSString *endPart = [phone substringWithRange:NSMakeRange(7, 4)];
        NSString *formatPhone = [NSString stringWithFormat:@"%@****%@",firstPart,endPart];
        return formatPhone;
    }else {
        return nil;
    }
}

+ (BOOL)validateTextField:(UITextField*)textField{
    if (textField == nil || [textField.text isEqualToString:@""]) {
        return NO;
    }else{
        return YES;
    }
}

+(BOOL)validateTextFieldPassword:(UITextField *)textField
{
    NSLog(@"textfield:::%d",(int)textField.text.length);
    
    if ([self validateTextField:textField] == YES) {
        
        if ( 7 < textField.text.length && textField.text.length < 21 ) {
        
            if ([textField.text rangeOfString:@" "].location == NSNotFound) {
                
                return YES;
            }
            else{
            
                return NO;
            }
        }
        else{
            
            return NO;
        }
    }
    else{
        
        return NO;
    }
}

+ (BOOL)validateText:(NSString *)text {
    
    if (text == nil || [text isEqualToString:@""]) {
        return NO;
    }else{
        return YES;
    }
}

+ (NSString *)JudgmentDateThroughID:(NSString *)cardId
{
    NSString *string = nil;
    
    string = [cardId substringWithRange:NSMakeRange(cardId.length - 12, 8)];
    
    NSString *dateString = [cardId substringWithRange:NSMakeRange(cardId.length - 6, 2)];
    
    NSString *monthString = [string substringWithRange:NSMakeRange(string.length - 4, 2)];
    
    string = [NSString stringWithFormat:@"%@%@%@",[string substringToIndex:4],monthString,dateString];
    
    return string;
}

+(NSString *)cardTypeChooseFromId:(NSString *)numberId
{
    NSString *string = nil;
    
    if ([numberId isEqual:@"08"] || [numberId isEqual:@"09"]) {
        
        numberId = [numberId substringFromIndex:1];
    }
    
    switch ([numberId intValue]) {
        case 01:
        {
            string = NSLocalizedString(@"ID", nil);
            break;
        }
        case 02:
        {
            string = NSLocalizedString(@"account_thin", nil);

            break;
        }
        case 03:
        {
            string = NSLocalizedString(@"military_ID", nil);

            break;
        }
        case 04:
        {
            string = NSLocalizedString(@"armed_police_ID", nil);

            break;
        }
        case 05:
        {
            string = NSLocalizedString(@"card_number_of_HongKong_and_Macao", nil);

            break;
        }
        case 06:
        {
            string = NSLocalizedString(@"taiwan_HVPs", nil);

            break;
        }
        case 07:
        {
            string = NSLocalizedString(@"national_passport", nil);

            break;
        }
        case 8:
        {
            string = NSLocalizedString(@"foreign_passport", nil);

            break;
        }
        case 9:
        {
            string = NSLocalizedString(@"temporary_ID_cards", nil);

            break;
        }
        case 10:
        {
            string = NSLocalizedString(@"military_soldiers_card", nil);

            break;
        }
        case 11:
        {
            string = NSLocalizedString(@"military_and_civilian_cadres_cards", nil);

            break;
        }
    }
    
    return string;
}

+(NSString *)calculationString:(NSString *)string
{
    NSString *_string = string;
    
    _string = [string substringWithRange:NSMakeRange(string.length - 2, 1)];
    
    if ([_string isEqual:@"0"]) {
        
        _string = [string substringWithRange:NSMakeRange(string.length - 1, 1)];
    }
    else{
        
        _string = string;
    }
    
    return _string;
}

+ (NSString *)JudgmentIsManOrWomanThroughID:(NSString *)cardId
{
    NSString *string = nil;
    NSInteger number = [[cardId substringWithRange:NSMakeRange(cardId.length-2, 1)] integerValue];
    if (number%2 == 1) {
        
        string = @"1";
    }
    else{
        
        string = @"2";
    }
    
    return string;
}


+ (NSDate *)dateFromString:(NSString *)dateStr{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *dateTime = [formatter dateFromString:dateStr];
    return dateTime;
}

+ (NSString*)timeToString:(NSDate *)time{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateStr = [formatter stringFromDate:time];
    NSLog(@"time str is : %@",dateStr);
    return dateStr;
}

//图片转换成base64数据的字符串
+ (NSString*)imageToString:(UIImage *)source{
    NSData *data = UIImageJPEGRepresentation(source, 1.0f);
    NSString *encodedImageStr = [data base64Encoding];
    return encodedImageStr;
}

//还原base64数据为图片
+ (UIImage*)stringToImage:(NSString *)source{
    NSData *decodedImageData = [NSData dataWithBase64EncodedString:source];
    UIImage *image = [UIImage imageWithData:decodedImageData];
    return image;
}

+ (NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(int)month
{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMonth:month];
    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
    return mDate;
}

+(int)GetDay:(NSDate *)date
{
	NSCalendar* calender = [NSCalendar currentCalendar];
	NSDateComponents* dateComp = [calender components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
	return (int)[dateComp day];
}

+(int)GetMonth:(NSDate *)date
{
	NSCalendar* calender = [NSCalendar currentCalendar];
	NSDateComponents* dateComp = [calender components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
	return (int)[dateComp month];
}

+(int)GetYear:(NSDate *)date
{
	NSCalendar* calender = [NSCalendar currentCalendar];
	NSDateComponents* dateComp = [calender components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
	return (int)[dateComp year];
}

+(NSString*)getMonthString:(int)month{
    NSArray *months = [NSArray arrayWithObjects:@"一月",@"二月",@"三月",@"四月",@"五月",@"六月",@"七月",@"八月",@"九月",@"十月",@"十一月",@"十二月", nil];
    NSString *string = [months objectAtIndex:(month-1)];
    return string;
}

+ (BOOL)validateEmail:(NSString *)candidate
{
    NSArray *array = [candidate componentsSeparatedByString:@"."];
    if ([array count] >= 4) {
        return FALSE;
    }
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}


/**
 * 功能:获取指定范围的字符串
 * 参数:字符串的开始小标
 * 参数:字符串的结束下标
 */
+(NSString *)getStringWithRange:(NSString *)str Value1:(NSInteger)value1 Value2:(NSInteger )value2
{
    return [str substringWithRange:NSMakeRange(value1,value2)];
}
/**
 * 功能:判断是否在地区码内
 * 参数:地区码
 */
+(BOOL)areaCode:(NSString *)code
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:@"北京" forKey:@"11"];
    [dic setObject:@"天津" forKey:@"12"];
    [dic setObject:@"河北" forKey:@"13"];
    [dic setObject:@"山西" forKey:@"14"];
    [dic setObject:@"内蒙古" forKey:@"15"];
    [dic setObject:@"辽宁" forKey:@"21"];
    [dic setObject:@"吉林" forKey:@"22"];
    [dic setObject:@"黑龙江" forKey:@"23"];
    [dic setObject:@"上海" forKey:@"31"];
    [dic setObject:@"江苏" forKey:@"32"];
    [dic setObject:@"浙江" forKey:@"33"];
    [dic setObject:@"安徽" forKey:@"34"];
    [dic setObject:@"福建" forKey:@"35"];
    [dic setObject:@"江西" forKey:@"36"];
    [dic setObject:@"山东" forKey:@"37"];
    [dic setObject:@"河南" forKey:@"41"];
    [dic setObject:@"湖北" forKey:@"42"];
    [dic setObject:@"湖南" forKey:@"43"];
    [dic setObject:@"广东" forKey:@"44"];
    [dic setObject:@"广西" forKey:@"45"];
    [dic setObject:@"海南" forKey:@"46"];
    [dic setObject:@"重庆" forKey:@"50"];
    [dic setObject:@"四川" forKey:@"51"];
    [dic setObject:@"贵州" forKey:@"52"];
    [dic setObject:@"云南" forKey:@"53"];
    [dic setObject:@"西藏" forKey:@"54"];
    [dic setObject:@"陕西" forKey:@"61"];
    [dic setObject:@"甘肃" forKey:@"62"];
    [dic setObject:@"青海" forKey:@"63"];
    [dic setObject:@"宁夏" forKey:@"64"];
    [dic setObject:@"新疆" forKey:@"65"];
    [dic setObject:@"台湾" forKey:@"71"];
    [dic setObject:@"香港" forKey:@"81"];
    [dic setObject:@"澳门" forKey:@"82"];
    [dic setObject:@"国外" forKey:@"91"];
    
    if ([dic objectForKey:code] == nil) {
        
        return NO;
    }
    return YES;
}

/**
 * 功能:验证身份证是否合法
 * 参数:输入的身份证号
 */
+(BOOL)Chk18PaperId:(NSString *)sPaperId{
    sPaperId = [sPaperId uppercaseString];
    
    //判断位数
    if ([sPaperId length] < 15 ||[sPaperId length] > 18) {
        
        return NO;
    }
    
    NSString *carid = sPaperId;
    long lSumQT =0;
    //加权因子
    int R[] ={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
    //校验码
    unsigned char sChecker[11]={'1','0','X', '9', '8', '7', '6', '5', '4', '3', '2'};
    
    //将15位身份证号转换成18位
    
    NSMutableString *mString = [NSMutableString stringWithString:sPaperId];
    if ([sPaperId length] == 15) {
        
        
        [mString insertString:@"19" atIndex:6];
        
        long p = 0;
        const char *pid = [mString UTF8String];
        for (int i=0; i<=16; i++)
        {
            p += (pid[i]-48) * R[i];
        }
        
        int o = p%11;
        NSString *string_content = [NSString stringWithFormat:@"%c",sChecker[o]];
        [mString insertString:string_content atIndex:[mString length]];
        carid = mString;
        
    }
    
    //判断地区码
    NSString * sProvince = [carid substringToIndex:2];
    
    if (![YMUtil areaCode:sProvince]) {
        
        return NO;
    }
    
    //判断年月日是否有效
    
    //年份
    int strYear = [[YMUtil getStringWithRange:carid Value1:6 Value2:4] intValue];
    //月份
    int strMonth = [[YMUtil getStringWithRange:carid Value1:10 Value2:2] intValue];
    //日
    int strDay = [[YMUtil getStringWithRange:carid Value1:12 Value2:2] intValue];
    
    
    NSTimeZone *localZone = [NSTimeZone localTimeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setTimeZone:localZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d 12:01:01",strYear,strMonth,strDay]];
    if (date == nil) {
        return NO;
    }
    
    const char *PaperId  = [carid UTF8String];
    
    //检验长度
    if( 18 != strlen(PaperId)) return -1;
    //校验数字
    for (int i=0; i<18; i++)
    {
        if ( !isdigit(PaperId[i]) && !(('X' == PaperId[i] || 'x' == PaperId[i]) && 17 == i) )
        {
            return NO;
        }
    }
    //验证最末的校验码
    for (int i=0; i<=16; i++)
    {
        lSumQT += (PaperId[i]-48) * R[i];
    }
    if (sChecker[lSumQT%11] != PaperId[17] )
    {
        return NO;
    }
    
    return YES;
}


+ (NSString*)randomString
{
    NSArray *array = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9", nil];
    NSMutableString *string = [[NSMutableString alloc] init];
    int count = (int)[array count];
    for (int i=0; i<32; i++) {
        int randomNum = arc4random()%count;
        [string appendString:[array objectAtIndex:randomNum]];
    }
    NSLog(@"%@",string);
    return string;
}

//add by peixb 产生4位随机数，生成一维码支付的时候，放在CUST_NO后面
+ (NSString *)createFourRandom
{
    return [NSString stringWithFormat:@"%d%d%d%d", arc4random()%10, arc4random()%10, arc4random()%10, arc4random()%10];
}


//将NSDictionary中的Null类型的项目转化成@""
+(NSDictionary *)nullDic:(NSDictionary *)myDic
{
    NSArray *keyArr = [myDic allKeys];
    NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
    for (int i = 0; i < keyArr.count; i ++)
    {
        id obj = [myDic objectForKey:keyArr[i]];
        
        obj = [self changeType:obj];
        
        [resDic setObject:obj forKey:keyArr[i]];
    }
    return resDic;
}

//将NSDictionary中的Null类型的项目转化成@""
+(NSArray *)nullArr:(NSArray *)myArr
{
    NSMutableArray *resArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < myArr.count; i ++)
    {
        id obj = myArr[i];
        
        obj = [self changeType:obj];
        
        [resArr addObject:obj];
    }
    return resArr;
}

//将NSString类型的原路返回
+(NSString *)stringToString:(NSString *)string
{
    return string;
}

//将Null类型的项目转化成@""
+(NSString *)nullToString
{
    return @"";
}

#pragma mark - 公有方法
//类型识别:将所有的NSNull类型转化成@""
+(id)changeType:(id)myObj
{
    if ([myObj isKindOfClass:[NSDictionary class]])
    {
        return [self nullDic:myObj];
    }
    else if([myObj isKindOfClass:[NSArray class]])
    {
        return [self nullArr:myObj];
    }
    else if([myObj isKindOfClass:[NSString class]])
    {
        return [self stringToString:myObj];
    }
    else if([myObj isKindOfClass:[NSNull class]])
    {
        return [self nullToString];
    }
    else
    {
        return myObj;
    }
}

@end
